<?php
/**
 * 将upyun上的文件队列下载到本地
 */
include_once('../lib/config.php');
include_once('../lib/Db.class.php');
include_once('../lib/Model.class.php');
include_once('../lib/Upyun.class.php');
include_once('../lib/function.php');

list($file, $path) = $argv;
if(!$path) $path = 'images';
$up_path = strtoupper($path);

$redis = new Redis();
$redis->connect(REDIS_IP, "6379");  //php客户端设置的ip及端口
if(!$redis) die('redis connect fail');
$redis->auth(REDIS_PASS);

$localDir = LIUDOUMI_DL_ROOT . '/images';

while (true) {
    $stop = $redis->get('LNPAN_QUEUE_STOP');
    if($stop) {
        die('stop');
    }

    /**
    $kcmd = 'ps aux | grep wget | grep upaiyun | wc -l';
    $result = shell_exec($kcmd);
    $result = (int) trim($result);
    var_dump($result);
    if($result > 10) {
        sleep(1);
        continue;
    }
    **/

    $filename = $redis->lPop('UPYUN_'.$up_path.'_QUEUE');
    if($filename) {
        $redis->rPush('UPYUN_'.$up_path.'_QUEUE_BAK', $filename);
        $url = 'http://liudoumi-file.b0.upaiyun.com/'.$path.'/' . $filename;

        $cmd  = 'cd '.$localDir.';';
        $cmd .= 'wget --limit-rate=1000k --continue --timeout=120 --tries=5 --no-clobber --debug --no-host-directories '.$url;
        $result = shell_exec($cmd);

        $localFile = $localDir .'/'. $filename;
        clearstatcache();
        $filesize = (int) filesize($localFile);
        if(!file_exists($localFile) || $filesize < 3000) {
            $redis->rPush('UPYUN_DOWN_QUEUE_NIL', $filename);
        }

    } else {
        sleep(1);
    }
}